<template>
    <Conference display-mode="permanent"></Conference>
</template>

<script setup lang="ts">
import Conference from '@/components/TUIRoom/conference.vue';

import { onMounted, onUnmounted } from 'vue';
import { conference, RoomEvent } from '@tencentcloud/roomkit-web-vue3';
import { onBeforeRouteLeave, useRoute } from 'vue-router';
import router from '@/router';
import { useI18n } from '@/locales/index';

const { t } = useI18n();

const route = useRoute();
const roomInfo = sessionStorage.getItem('tuiRoom-roomInfo');
const userInfo = sessionStorage.getItem('tuiRoom-userInfo');
const roomId = String(route.query.roomId);
let isMaster = false;
let isExpectedJump = false;

if (!roomId) {
    router.push({ path: 'home' });
} else if (!roomInfo) {
    router.push({ path: 'home', query: { roomId } });
}

onMounted(async () => {
    const { action, isSeatEnabled, roomParam, hasCreated } = JSON.parse(roomInfo as string);
    const { sdkAppId, userId, userSig, userName, avatarUrl } = JSON.parse(userInfo as string);
    if (action === 'createRoom') {
        isMaster = true;
    }
    try {
        await conference.login({ sdkAppId, userId, userSig });
        await conference.setSelfInfo({ userName, avatarUrl });
        conference.setTheme('LIGHT');
        if (action === 'createRoom' && !hasCreated) {
            console.log(222222222, roomParam);

            await conference.start(roomId, {
                roomName: `${userName || userId}${t('Quick Conference')}`,
                isSeatEnabled,
                ...roomParam,
            });
            const newRoomInfo = { action, roomId, roomName: roomId, isSeatEnabled, roomParam, hasCreated: true };
            sessionStorage.setItem('tuiRoom-roomInfo', JSON.stringify(newRoomInfo));
        } else {
            await conference.join(roomId, roomParam);
        }
    } catch (error: any) {
        sessionStorage.removeItem('tuiRoom-currentUserInfo');
    }
});

onBeforeRouteLeave((to: any, from: any, next: any) => {
    if (!isExpectedJump) {
        const message = isMaster
            ? t('This action causes the room to be disbanded, does it continue?')
            : t('This action causes the room to be exited, does it continue?');
        if (window.confirm(message)) {
            if (isMaster) {
                conference?.dismiss();
            } else {
                conference?.leave();
            }
            next();
        } else {
            next(false);
        }
    } else {
        next();
    }
});

const backToPage = (page:string, shouldClearUserInfo: boolean) => {
    sessionStorage.removeItem('tuiRoom-roomInfo');
    shouldClearUserInfo && sessionStorage.removeItem('tuiRoom-currentUserInfo');
    goToPage(page);
};
const backToHome = () => backToPage('home', false);
const backToHomeAndClearUserInfo = () => backToPage('home', true);
conference.on(RoomEvent.ROOM_DISMISS, backToHome);
conference.on(RoomEvent.ROOM_LEAVE, backToHome);
conference.on(RoomEvent.KICKED_OUT, backToHome);
conference.on(RoomEvent.ROOM_ERROR, backToHome);
conference.on(RoomEvent.KICKED_OFFLINE, backToHome);
conference.on(RoomEvent.USER_SIG_EXPIRED, backToHomeAndClearUserInfo);
conference.on(RoomEvent.USER_LOGOUT, backToHomeAndClearUserInfo);

onUnmounted(() => {
    conference.off(RoomEvent.ROOM_DISMISS, backToHome);
    conference.off(RoomEvent.ROOM_LEAVE, backToHome);
    conference.off(RoomEvent.KICKED_OUT, backToHome);
    conference.off(RoomEvent.ROOM_ERROR, backToHome);
    conference.off(RoomEvent.KICKED_OFFLINE, backToHome);
    conference.off(RoomEvent.USER_SIG_EXPIRED, backToHomeAndClearUserInfo);
    conference.off(RoomEvent.USER_LOGOUT, backToHomeAndClearUserInfo);
});

const goToPage = (routePath: string) => {
    isExpectedJump = true;
    router.replace({ path: routePath });
};
</script>

<style lang="scss">
#app {
  font-family: PingFang SC;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  position: relative;
  width: 100%;
  height: 100%;
}
</style>
